package com.dmw.dao.impl;


import com.dmw.dao.IUserDao;
import com.dmw.pojo.User;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Repository
public class IUserDaoImpl implements IUserDao {
    @PersistenceContext(name = "entityManagerFactory")
    private EntityManager manager;

    @Override
    public void addUser(User user) {
        manager.persist(user);
    }

    @Override
    public void alterUser(User user) {
        manager.merge(user);
    }

    @Override
    public void removeUser(User user) {
        User userRes = this.findUserById(user.getUserId());
        manager.remove(userRes);
    }

    @Override
    public User findUserById(Integer userId) {
        User user = manager.find(User.class, userId);
        return user;
    }

    @Override
    public List<User> findUserByNameByHQL(String userName) {
        Query query = manager.createQuery(" from User where userName = :abc" );
              query = query.setParameter("abc", userName);
        List  list  =  query.getResultList();
        return list;
    }

    @Override
    public List<User> findUserByNameBySQL(String userName) {
        List list = manager.createNativeQuery("select * from t_user where user_name = ?", User.class)
                .setParameter(1, userName)
                .getResultList();
        return list;
    }

    @Override
    public List<User> findUserByNameByCriteria(String userName) {
        CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
        CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);
        Root<User> root = query.from(User.class);
        Predicate pred = criteriaBuilder.equal(root.get("userName"), userName);
        query.where(pred);
        TypedQuery<User> typedQuery = manager.createQuery(query);
        return typedQuery.getResultList();
    }
}
